package stack;

import java.util.Arrays;

/**
 * 数组实现栈
 */
public class StackArray <T>{

    //实现栈的数组
    private Object[] stack;
    //最新存储数据下标
    private int index = 0;

    public StackArray() {
        stack = new Object[10];
    }

    //扩大容量
    private void expandCapacity() {
        int length = stack.length;
        if (index < length){
            return;
        }
        length = length * 3 / 2 + 1;//每次扩大50%
        stack = Arrays.copyOf(stack, length);
    }

    /**
     * 出栈
     */
    public T pop(){
        T t = peek();
        if (index > 0){
            stack[index-1] = null;
            --index;
        }
        return t;
    }

    /**
     * 入栈
     */
    public void push(T t){
        expandCapacity();
        stack[index] = t;
        ++index;
    }

    /**
     * 取出栈顶元素
     */
    public T peek(){
        if (index == 0){
            return null;
        }
        return (T) stack[index-1];
    }

    /**
     * 栈深度
     */
    public int length(){
        return index;
    }

    /**
     * 是否为空栈
     */
    public boolean isEmpty(){
        return index == 0;
    }

    /**
     * 清空栈
     */
    public void clear(){
        stack = new Object[10];
        index = 0;
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        for (int i=0; i<index; ++i){
            if (!str.toString().isEmpty()){
                str.append(",");
            }
            str.append(stack[i]);
        }
        str.insert(0, "[").append(']');
        return str.toString();
    }
}
